package ddz.logic.game;

import ch.qos.logback.classic.Logger;
import com.kaka.notice.Command;
import com.kaka.notice.Message;
import com.kaka.notice.annotation.Handler;
import com.kaka.util.MathUtils;
import ddz.constants.Crypto;
import ddz.constants.OpCode;
import ddz.core.Table;
import ddz.core.Player;
import ddz.db.dao.TableDao;
import ddz.net.WsSender;
import ddz.protos.Game;
import ddz.protos.GameFapai;
import org.slf4j.LoggerFactory;

/**
 * 发牌
 *
 * @author zkpursuit
 */
@Handler(cmd = OpCode.cmd_fapai, type = String.class)
public class FaPaiHandler extends Command implements WsSender {

    private static final Logger logger = (Logger) LoggerFactory.getLogger(FaPaiHandler.class);

    @Override
    public void execute(Message message) {
        Table table = (Table) message.getBody();
        table.clearRecords();
        table.distribute();
        Player[] members = table.getPlayers();
        int bankerSeatIdx = MathUtils.random(0, members.length - 1); //随机庄家的座位索引
        table.setBankerSeatIndex(bankerSeatIdx);
        if (logger.isInfoEnabled()) logger.info("随机庄家：" + bankerSeatIdx);
        table.setFapaiStartTime(System.currentTimeMillis());
        for (Player player : members) {
            if (player != null) {
                byte[] bytes = buildPlayerCards(player.getUid(), table).toByteArray();
                this.sendData(player.getUid(), Crypto.isCrypto, Integer.parseInt(OpCode.cmd_fapai), bytes);
            }
        }
        TableDao tableDao = this.retrieveProxy(TableDao.class);
        tableDao.insertOrUpdateDesk(table);
        logger.info("已为房间[{}]进行发牌处理", table.getId());

        //QuartzFacade quartzFacade = (QuartzFacade) this.getFacade();
        //Date date = new Date(System.currentTimeMillis() + 4500);
        //quartzFacade.sendMessage(new Message(OpCode.timer_fapai, desk.getId()), "desk:" + desk.getId(), date);
        this.sendMessage(new Message(OpCode.timer_fapai, table.getId()));
    }

    /**
     * 保证每个玩家获得的牌数据仅仅只有自己的牌
     *
     * @param uid
     * @param table
     * @return
     */
    public GameFapai.ScFapai buildPlayerCards(long uid, Table table) {
        Player[] members = table.getPlayers();
        GameFapai.ScFapai.Builder fapaiBuilder = GameFapai.ScFapai.newBuilder();
        int[] diPai = table.getDiCards();
        for (int i = 0; i < members.length; i++) {
            Player player = members[i];
            Game.PlayerCards.Builder playerCardsBuilder = Game.PlayerCards.newBuilder();
            playerCardsBuilder.setSeat(player.getSeatIndex());
            int[] cards = player.getMycards().getCards();
            Game.Cards.Builder cardsBbuilder = Game.Cards.newBuilder();
            for (int j = 0; j < cards.length; j++) {
                if (uid == player.getUid() || table.isMingPai(i)) {
                    cardsBbuilder.addCard(cards[j]);
                } else {
                    cardsBbuilder.addCard(0);
                }
            }
            fapaiBuilder.addPlayerCards(playerCardsBuilder.setCards(cardsBbuilder.build()));
        }
        Player player = table.getPlayerByUid(uid);
        if (player.isPriorLookDiPai() && diPai.length == 3) {
            for (int card : diPai) {
                fapaiBuilder.addDiPai(card);
            }
        }
        return fapaiBuilder.build();
    }

}
